<template>
   <a-spin :spinning="confirmLoading">
     <j-form-container :disabled="formDisabled">
       <!-- 主表单区域 -->
       <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
         <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="盘点编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入盘点编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="盘点仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="repositoryName">
              <j-popup
                v-model="model.repositoryName"
                field="repositoryName"
                org-fields="name,code"
                dest-fields="repositoryName,repositoryCode"
                code="select_repository"
                :multi="false"
                @input="popupCallback"
                />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="盘点日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="checkTime">
              <j-date placeholder="请选择盘点日期" v-model="model.checkTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="盘点人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="personName">
              <j-select-user-by-dep v-model="model.personName" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea v-decorator="['remark']" rows="4" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
     </j-form-container>
      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="盘点明细" :key="refKeys[0]" :forceRender="true">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="purchaseStockCheckDetailTable.loading"
            :columns="purchaseStockCheckDetailTable.columns"
            :dataSource="purchaseStockCheckDetailTable.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="!model.id"
            @valueChange="valueChange"
            />
        </a-tab-pane>
      </a-tabs>
    </a-spin>
</template>

<script>

  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import {stockCheck} from '@/api/api'
  import currency from 'currency.js'

  export default {
    name: 'PurchaseStockCheckForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
          code:''
        },
        validatorRules: {
          repositoryName: [
            { required: true, message: '请选择盘点仓库'},
          ],
          checkTime: [
            { required: true, message: '请选择盘点日期'},
          ],
          personName: [
            { required: true, message: '请选择盘点人'},
          ],
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        refKeys: ['purchaseStockCheckDetail', ],
        tableKeys:['purchaseStockCheckDetail', ],
        activeKey: 'purchaseStockCheckDetail',
        // 盘点明细
        purchaseStockCheckDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物品名称',
              key: 'goodsName',
              type: FormTypes.popup,
              popupCode:"stock_select",
              destFields:"goodsName,goodsTypeCode,goodsCode,size,unit,unitPrice,brand,repositoryNumber",
              orgFields:"goods_name,goods_type_code,goods_code,goods_size,goods_unit,goods_unit_price,brand,total_number",
              width:"200px",
              param:{},
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物品分类',
              key: 'goodsTypeCode',
              type: FormTypes.select,
              dictCode:"purchase_goods_type",
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物品编码',
              key: 'goodsCode',
              type: FormTypes.input,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '品牌',
              key: 'brand',
              type: FormTypes.input,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '规格/尺寸/型号',
              key: 'size',
              type: FormTypes.input,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单位',
              key: 'unit',
              type: FormTypes.select,
              dictCode:"purchase_unit",
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单价',
              key: 'unitPrice',
              type: FormTypes.input,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [
                {pattern: /^\d+(\.{0,1}\d+){0,1}$/, message: '${title}必须非负数'}
              ],
            },
            {
              title: '库存数量',
              key: 'repositoryNumber',
              type: FormTypes.inputNumber,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '盘点数量',
              key: 'checkNumber',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [
              {
                handler(type, value, row, column, callback, target) {
                  let { values } = target.getValuesSync({ validate: false, rowIds: [row.id] })
                  const num = Number(values[0].checkNumber)
                  if (!num){
                    callback(false, `盘点数量不能为空`)
                  } else {
                    callback(true)
                  }
                },
                message: '${title}默认提示',
              },
            ],
            },
            {
              title: '盈亏数量',
              key: 'profitLoss',
              type: FormTypes.inputNumber,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },

            {
              title: 'goods_name',
              key: 'goods_name',
              type:"hidden"
            },

            {
              title: 'goods_type_code',
              key: 'goods_type_code',
              type:"hidden"
            },

            {
              title: 'goods_code',
              key: 'goods_code',
              type:"hidden"
            },



            {
              title: 'unit_price',
              key: 'unit_price',
              type:"hidden"
            },


            {
              title: 'repository_number',
              key: 'repository_number',
              type:"hidden"
            },
          ]
        },
        url: {
          add: "/purchase/purchaseStockCheck/add",
          edit: "/purchase/purchaseStockCheck/edit",
          purchaseStockCheckDetail: {
            list: '/purchase/purchaseStockCheck/queryPurchaseStockCheckDetailByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    
    },
    methods: {
      valueChange(obj){
        // console.log(obj)
        if(obj.row.repositoryNumber >= 0 && obj.row.checkNumber >= 0){
          // let sub_total = obj.row.unitPrice * obj.row.number
          let sub_total = currency(obj.row.checkNumber).subtract(obj.row.repositoryNumber)
            if(sub_total != obj.row.profitLoss){
              obj.target.setValues([{
                rowKey: obj.row.id,
                values: {
                  'profitLoss': sub_total
                }
              }])
            }
        }
        // obj.target.getValues((error,values) => {
        //   let total = 0
        //   values.map(item => {
        //     // total += item.total
        //     total =currency(total).add(item.total)
        //   })
        //   console.log(total)
        //   this.model.total = total.value
        // })
      },
      //初始化库存盘点编码
      init(){
        stockCheck({}).then((res)=>{
          if(res.success){
            this.model.code = res.result;
          }else{
            this.$message.warning(res.message);
          }
        });
      },
     addBefore(){
            this.purchaseStockCheckDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.purchaseStockCheckDetail.list, params, this.purchaseStockCheckDetailTable)
        }
        if(!this.model.id){
          this.init();
        }
        this.purchaseStockCheckDetailTable.columns[0].param = {
          repositoryCode: this.model.repositoryCode,
        }
      },
      //校验所有一对一子表表单
    validateSubForm(allValues){
        return new Promise((resolve,reject)=>{
          Promise.all([
          ]).then(() => {
            resolve(allValues)
          }).catch(e => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
        })
    },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)

        return {
          ...main, // 展开
          purchaseStockCheckDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
     close() {
        this.visible = false
        this.$emit('close')
        this.$refs.form.clearValidate();
      },
     popupCallback(value,row){
        this.model = Object.assign(this.model, row);
        this.purchaseStockCheckDetailTable.columns[0].param = row;
     },

    }
  }
</script>

<style scoped>
</style>